import numpy as np
import csv
from datetime import datetime
from time import strftime


def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = int(float(record[item]))
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def cal_dist(x1, y1, x2, y2):
    temp_dist = (float(x1 - x2))**2 + (float((y1 - y2))**2)
    #print x1, y1, x2, y2, (float(x1 - x2))**2, (float((y1 - y2))**2), temp_dist
    temp_dist = temp_dist**0.5
    #print temp_dist

    return temp_dist

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    print "begin at " + getCurTime()

    filepath = 'C:/_DATA/migration_census_2000/'
    #filepath = 'C:/_DATA/migration89_08/COUNTY Migration/clean/test/US_census_pop_2011_county_id.csv'

    dataCSV = filepath + 'census_county_migration_format.csv'
    data = build_data_list(dataCSV)

    print data

    CentroidCSV = filepath + 'census_county_centroid.csv'
    centroid = build_data_list(CentroidCSV)

    print centroid

    inflow = np.zeros(len(centroid))
    outflow = np.zeros(len(centroid))

    for item in data:
        inflow[item[1]] += item[-1]
        outflow[item[0]] += item[-1]

    print inflow, sum(inflow)
    print outflow, sum(outflow)

    totalflow = sum(data[:,-1])
    expSum = 0
    
    output = []

    #hist_10bin = np.zeros(500)
    #hist_20bin = np.zeros(250)
    #hist_50bin = np.zeros(100)
    output = np.zeros((100,10))


    for item in data:
        temp = int(item[0]/10000)
        hist_bin[temp] += item[-1]
    
    for i in range(len(centroid)):
        for j in range(len(centroid)):
            if (i > -1):
                dist = int(cal_dist(centroid[i, 0], centroid[i, 1], centroid[j, 0], centroid[j, 1]))
                temp = int(dist/50000)
                for b in range(1,11):
                    exp = (inflow[i] * outflow[j])**(0.1 * b) / totalflow
                    output[temp,b-1] += exp

        
    #fileLoc = filePath + 'census_county_migration_expFlow_dist_10k_bin.csv'
    #np.savetxt(fileLoc, hist_10bin, delimiter=',', fmt = '%s')
    #fileLoc = filePath + 'census_county_migration_expFlow_dist_20k_bin.csv'
    #np.savetxt(fileLoc, hist_20bin, delimiter=',', fmt = '%s')
    fileLoc = filePath + 'census_county_migration_expFlow_dist_50k_bin_all.csv'
    np.savetxt(fileLoc, output, delimiter=',', fmt = '%s')
    #np.savetxt(filepath + 'gravity_model_data.csv', output, delimiter=',', fmt = '%s')